package wechat;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import enums.DeletedStatus;
import models.base.BaseModel;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 验证码 保存
 */
@Entity
@Table(name="temp_captcha")
public class TempCaptcha extends BaseModel {

    /**
     * 手机号码
     */
    @Column(name="phone")
    public String phone ;

    /**
     * 验证码
     */
    @Column(name="captcha")
    public String captcha ;

    /**
     * 有效时间
     */
    @Column(name="end_at")
    @Temporal(TemporalType.TIMESTAMP)
    public Date endAt ;


    /**
     * 生成验证码
     * @param phone
     * @return
     */
    public static TempCaptcha  create(String phone){

        TempCaptcha tempCaptcha = TempCaptcha.findByPhone(phone);
        Date nowTime = new Date();
        if(tempCaptcha == null) {
            tempCaptcha = new TempCaptcha();
            tempCaptcha.deleted = DeletedStatus.UN_DELETED;
            tempCaptcha.createAt = nowTime;
            tempCaptcha.phone = phone;
        }
        tempCaptcha.captcha = RandomUtil.randomNumbers(6) ;
        //有效时间，1分钟
        tempCaptcha.endAt = DateUtil.offset(nowTime , DateField.MINUTE, 1);
        tempCaptcha.save();
        return  tempCaptcha ;
    }
    /**
     * 验证手机号，验证码，是否有效
     * @param phone
     * @param captcha
     * @return
     */
    public static TempCaptcha validateCaptcha(String phone , String captcha){
        return  TempCaptcha.find("phone = ?1 and captcha =?2 and endAt > ?3" , phone , captcha , new Date()).first();
    }

    /**
     *
     * @param phone
     * @return
     */
    public static TempCaptcha findByPhone(String phone){
        return TempCaptcha.find("phone = ?1" , phone).first();
    }


}